package commRedisTag

import (
	"errors"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Map"
	"sync"
)

type redisTagService struct {
	mutex           sync.Mutex
	consumerData    map[string]interface{}
	producerData    map[string]interface{}
	consumerSyncTag int64
	producerSyncTag bool
}

func (e *redisTagService) load() error {
	e.mutex.Lock()
	defer e.mutex.Unlock()

	// 读取总标记
	redisSync, err := reader.readTagsSync()
	if err != nil {
		return err
	}

	// 检查：总标记是否发生了变化
	if e.consumerSyncTag == redisSync {
		return nil
	}

	// 读取具体数据
	tags, err := reader.readTags()
	if err != nil {
		return err
	}
	if tags == nil {
		return errors.New("返回数据为空")
	}

	// 填写新数据
	Map.Append(e.consumerData, tags)

	// 删除老数据
	keys := make(map[string]interface{})
	Map.Append(keys, e.consumerData)
	for k := range keys {
		value := tags[k]
		if value == nil {
			continue
		}

		delete(e.consumerData, k)
	}

	return nil
}

func (e *redisTagService) save() {
	e.mutex.Lock()
	defer e.mutex.Unlock()

	if !e.producerSyncTag {
		return
	}

	writer.writeTags(e.producerData)
	e.producerSyncTag = false
}

func (e *redisTagService) SetValue(key string, value interface{}) {
	e.mutex.Lock()
	defer e.mutex.Unlock()

	e.producerData[key] = value
	e.producerSyncTag = true
}
